const fs = require("fs");
const _ = require("lodash");
const bodyParser = require("koa-body");
const dealMiddleware = require("./middleware");
const { init } = require("./router");
const filePath = __dirname + "/../../../module/";
//转发请求
function dealRequest(app) {
  //获取POST的BODY
  const maxFileSize = app.config.body?.maxFileSize;
  app.use(
    bodyParser({
      multipart: true,
      formidable: {
        maxFileSize: maxFileSize || 200 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
      },
    })
  );
  //引入所有文件
  require("young-require-all")({
    dirname: filePath,
    filter: /(.+)\.ts$/,
    resolve: function () {},
  });
  //处理中间件
  dealMiddleware(app);
  //注册路由
  app.use(async (ctx) => {
    //判断是否为文件
    const url = ctx.request.url;
    if (url.split("?")[0].indexOf(".") >= 0) {
      const fp = url.split("?")[0].replace("/", "");
      if (fs.existsSync(fp)) {
        //判断是否存在该文件
        try {
          let result = fs.readFileSync(fp);
          const suffix = url.split("?")[0].split(".");
          if (suffix[suffix.length - 1] == "css")
            ctx.type = "text/css; charset=utf-8";
          ctx.body = result;
        } catch (e) {
          ctx.status = 200;
          ctx.body = "file read field";
        }
      } else {
        ctx.status = 404;
        ctx.body = "";
      }
    } else {
      app.router = [];
      //初始化路由信息
      init(app, ctx);
      ctx.app = app;
      //查询对应的路由
      const router = _.find(app.router, {
        path: ctx.request.url.split("?")[0],
        method: ctx.request.method.toLowerCase(),
      });
      if (!router) {
        if (ctx.request.url.split("?")[0] === "/") {
          ctx.body = "hello young!";
        } else {
          ctx.status = 404;
          ctx.body = "not found";
        }
      } else {
        //实例化请求类
        const classLoad = new router.class(ctx);
        const result = await classLoad[router.func]();
        //对于一些已经在service层做处理的，这边不再重复处理
        if (!ctx.body) ctx.body = result || "";
      }
    }
  });
}
module.exports = dealRequest;
